//
//  ContactListViewController.m
//  Gildata
//
//  Created by 陆惠国 on 11-8-2.
//  Copyright 2011年 恒生聚源. All rights reserved.
//

#import "RosterViewController.h"
#import "RosterCell.h"
#import "SectionInfo.h"
#import "SectionHeaderView.h"
#import "XMPPClient.h"
#import "RosterTitleView.h"
#import "TTBaseNavigator+Popover.h"

#define DEFAULT_ROW_HEIGHT 44
#define HEADER_HEIGHT 30

@implementation RosterViewController

@synthesize tableView = _tableView;
@synthesize toolbar = _toolbar;
@synthesize sections = _sections;
@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize rosterTitleView = _rosterTitleView;
@synthesize searchBar = _searchBar;
@synthesize searchDisplay = _searchDisplay;
@synthesize savedSearchTerm = _savedSearchTerm;
@synthesize searchWasActive = _searchWasActive;
@synthesize active = _active;


#pragma mark - Init/dealloc
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.title = @"好友";
//        self.navigationController.navigationBar.tintColor = TTSTYLEVAR(navigationBarTintColor);
        self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:@"好友" image:[UIImage imageNamed:@"group.png"] tag:0] autorelease];  
        self.navigationItem.titleView = self.rosterTitleView;
        UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
        [swipeGesture setDirection:(UISwipeGestureRecognizerDirectionRight)]; 
        [self.rosterTitleView addGestureRecognizer:swipeGesture];
        [swipeGesture release];
        
        swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
        [swipeGesture setDirection:(UISwipeGestureRecognizerDirectionLeft)]; 
        [self.rosterTitleView addGestureRecognizer:swipeGesture];
        [swipeGesture release];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarTapped:)];
        [self.rosterTitleView.avatarView addGestureRecognizer:tapGesture];
        [tapGesture release];
        
        if(TTIsPad()){
            [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleSettingsChanged:) name: kSettingsChangedNotification object: nil]; 
        }

        
  
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    _fetchedResultsController.delegate = nil;
    TT_RELEASE_SAFELY(_tableView);
    TT_RELEASE_SAFELY(_toolbar);
    
    TT_RELEASE_SAFELY(_fetchedResultsController); 
    TT_RELEASE_SAFELY(_sections); 
    TT_RELEASE_SAFELY(_rosterTitleView); 
    TT_RELEASE_SAFELY(_searchBar); 
    TT_RELEASE_SAFELY(_searchDisplay); 
    [super dealloc];
}


#pragma mark - View lifecycle
- (void)loadView {

    [super loadView];

    if (TTIsPad()) {
        self.tableView.frame = CGRectMake(0.0f, 0.0f, self.view.width,
                                          self.view.height-TTToolbarHeight());
        [self.view addSubview:self.toolbar];
    }else{
        self.tableView.frame = CGRectMake(0.0f, 0.0f, self.view.width,
                                          self.view.height);

    }

    
    self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 44)] autorelease];
    self.searchBar.delegate = self;
    //self.searchBar.showsCancelButton = YES;
    self.searchBar.barStyle=UIBarStyleDefault;
    self.searchBar.placeholder=@"搜索";
    self.tableView.tableHeaderView = self.searchBar;
    self.searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
    self.searchDisplay.delegate = self;
    self.searchDisplay.searchResultsDataSource = self;
    self.searchDisplay.searchResultsDelegate = self;
    

    
    
}


- (void)viewDidLoad {
	
    [super viewDidLoad];
    
    // Set up default values.    
    self.tableView.sectionHeaderHeight = HEADER_HEIGHT;
    
    if (self.savedSearchTerm)
	{
        [self.searchDisplay setActive:self.searchWasActive];
        self.savedSearchTerm = nil;
    }
    

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    TT_RELEASE_SAFELY(_tableView);
    TT_RELEASE_SAFELY(_toolbar); 
    TT_RELEASE_SAFELY(_rosterTitleView); 
    TT_RELEASE_SAFELY(_searchBar);   
    TT_RELEASE_SAFELY(_searchDisplay);

}


- (void)viewWillAppear:(BOOL)animated
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    self.active = YES;
    [self fetchRosters];
    [self reloadData];
    [self reloadAvatar];
    
	[super viewWillAppear:animated];
    

}


- (void)viewWillDisappear:(BOOL)animated {
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);   

    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    self.searchWasActive = [self.searchDisplay isActive];
    self.savedSearchTerm = [self.searchDisplay.searchBar text];
    self.active = NO;
    [super viewDidDisappear:animated];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
    if (TTIsPad()) {
        return YES;
        
    } else {
        return interfaceOrientation == UIInterfaceOrientationPortrait;
    }
}

#pragma mark - Controls
- (UITableView*) tableView
{
    if (_tableView == nil)
	{
        _tableView = [[UITableView alloc] initWithFrame:
                             CGRectMake(0.0f, 0.0f, self.view.width,
                                        self.view.height-TTToolbarHeight())];
        _tableView.clearsContextBeforeDrawing = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.contentInset = UIEdgeInsetsMake(7.0f, 0.0f, 0.0f, 0.0f);
//        _tableView.backgroundColor = CHAT_BACKGROUND_COLOR;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
        UIViewAutoresizingFlexibleHeight;
        [self.view addSubview: _tableView];
	}
	
	return _tableView;    
}

- (UIToolbar*) toolbar
{
    if (_toolbar == nil)
	{
        _toolbar= [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.height - TTToolbarHeight(),
                                                              self.view.width, TTToolbarHeight())];
        _toolbar.autoresizingMask =
        UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
        _toolbar.tintColor = TTSTYLEVAR(toolbarTintColor); 
        UIBarItem* space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:
                             UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
        UIBarButtonItem* logoutButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"logout"] style:UIBarButtonItemStylePlain target:self action:@selector(logoutAction:)] autorelease];
        
        UIBarButtonItem* settingsButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingsAction:)] autorelease];
        UIBarButtonItem* aboutButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"about"] style:UIBarButtonItemStylePlain target:self action:@selector(aboutAction:)] autorelease];
        _toolbar.items = [NSArray arrayWithObjects: space, logoutButton, space, settingsButton, space, aboutButton, space, nil];
	}
	
	return _toolbar;    
}

- (void)logoutAction:(id) sender
{
    [[TTNavigator navigator] dismissPopoverAnimated:YES];

    UIAlertView* logoutAlert = [[UIAlertView alloc] initWithTitle:@"确认注销" message:@"确认要重新登录吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    
    [logoutAlert show];
    [logoutAlert release];

}

-(void) settingsAction: (id)sender
{
    if (TTIsPad()) {
        
        TTURLAction* action = [[[TTURLAction actionWithURLPath:@"gabber://settings"] applySourceButton:sender] applyAnimated:YES];
        [[TTNavigator navigator] openURLAction:action];
    }    
}

-(void) aboutAction: (id)sender
{
    if (TTIsPad()) {

        TTURLAction* action = [[[TTURLAction actionWithURLPath:@"gabber://about"] applySourceButton:sender] applyAnimated:YES];
        [[TTNavigator navigator] openURLAction:action];
    }
}


- (RosterTitleView*) rosterTitleView
{
    if (_rosterTitleView == nil)
	{
        _rosterTitleView= [[RosterTitleView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 44)];

	}
	
	return _rosterTitleView;    
}

#pragma mark - NSFetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController
{
	if (_fetchedResultsController == nil)
	{
		NSManagedObjectContext *moc = [[XMPPClient sharedInstance] managedObjectContext_roster];
		
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
		                                          inManagedObjectContext:moc];
		
		NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"sectionNum" ascending:YES];
		NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];
		
     
        NSPredicate *predicate;
        if(TTIsStringWithAnyText([self.searchBar text])){
            NSString* term= [NSString stringWithFormat:@"*%@*",[self.searchBar text]];
            
            predicate= [NSPredicate predicateWithFormat:@"streamBareJidStr == %@ AND (jidStr like[cd] %@ OR nickname like %@)",
                         [[[[XMPPClient sharedInstance] xmppStream]myJID] bare],term,term];
        }else{
            predicate=[NSPredicate predicateWithFormat:@"streamBareJidStr == %@",
                         [[[[XMPPClient sharedInstance] xmppStream]myJID] bare]];
        }

        
		NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
		
		NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
		[fetchRequest setEntity:entity];
        [fetchRequest setPredicate:predicate];
		[fetchRequest setSortDescriptors:sortDescriptors];
		[fetchRequest setFetchBatchSize:10];
		
		_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                        managedObjectContext:moc
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];
		[_fetchedResultsController setDelegate:self];
		//[predicate release];
		[sd1 release];
		[sd2 release];
		[fetchRequest release];
		
        
        
	}
	
	return _fetchedResultsController;
}

- (void)reloadAvatar{
	
    XMPPvCardTemp* vCardTemp = [[[XMPPClient sharedInstance] xmppvCardTempModule] myvCardTemp];
    XMPPUserCoreDataStorageObject* user = [[XMPPClient sharedInstance] myUser];
    
    NSString* name = [[[[XMPPClient sharedInstance] xmppStream] myJID] bare];
 
      
    if (user && TTIsStringWithAnyText(user.displayName)){

        name = user.displayName;
    }
    
    if (vCardTemp && TTIsStringWithAnyText(vCardTemp.formattedName)){
        name = vCardTemp.formattedName;
    }
    
    if (vCardTemp && TTIsStringWithAnyText(vCardTemp.nickname)){
        name = vCardTemp.nickname;
    }
    

    
    [self.rosterTitleView setAvatarImage: [[XMPPClient sharedInstance] myAvatar]];

    
    [self.rosterTitleView setName:name];

    
    XMPPPresence* myPresence =  [[[XMPPClient sharedInstance] xmppStream] myPresence];
    
    NSString* msg = myPresence.status;
    
    if(!TTIsStringWithAnyText(msg)){
        msg = myPresence.show;
    }
    
    if(!TTIsStringWithAnyText(msg)){
        msg = myPresence.type;
    }
    
    [self.rosterTitleView setStatus:msg];
    [self.rosterTitleView setIntShow:myPresence.intShow];
    
}

- (void)fetchRosters
{
    TT_RELEASE_SAFELY(_fetchedResultsController);
    
    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error])
    {
        DDLogWarn(@"Error performing fetch: %@", error);
    }      
}

- (void)loadRosters {
	DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    @try {
        BOOL showEmptyGroup = [[NSUserDefaults standardUserDefaults] boolForKey: kShowEmptyGroup];
        BOOL showOfflineUsers = [[NSUserDefaults standardUserDefaults] boolForKey: kShowOfflineUsers];
        BOOL groupOfflineUsers = [[NSUserDefaults standardUserDefaults] boolForKey: kGroupOfflineUsers];
        BOOL openGroups = [[NSUserDefaults standardUserDefaults] boolForKey: kOpenGroups];
        
        NSArray* users= [self.fetchedResultsController fetchedObjects]; 
        
        
        NSMutableDictionary* states = [NSMutableDictionary dictionary];
        for (SectionInfo* section in self.sections) {
            [states setObject:[NSNumber numberWithBool:section.open] forKey:section.sectionName];
        }
        
        self.sections = [NSMutableArray array];
        
        NSMutableDictionary* sectionDict = [NSMutableDictionary dictionary];
        SectionInfo* contacts = [SectionInfo sectionInfoWithName:@"我的联系人" open:openGroups];
        SectionInfo* offline = [SectionInfo sectionInfoWithName:@"离线"  open:NO];
        NSMutableDictionary* loaded = [NSMutableDictionary dictionary];
        for (XMPPUserCoreDataStorageObject* user in users) {
            
            if ([loaded objectForKey:user.jidStr]){
                break;
            }
            [loaded setObject:user forKey:user.jidStr];
            
            NSSet* groups = user.groups;
            if(groups && groups.count >0){
                for (XMPPGroupCoreDataStorageObject* group in groups){
                    NSString* name= group.name;
                    SectionInfo* section = [sectionDict objectForKey:name];
                    if (!section) {
                        section = [SectionInfo sectionInfoWithName:name open:openGroups];
                        [sectionDict setObject:section forKey:name];
                    }
                    if (user.section == 0 ||user.section == 1 ) {
                        [section.items addObject:user];
                    }else{
                        if (showOfflineUsers) {
                            if (groupOfflineUsers) {
                                [offline.items addObject:user];
                            }else{
                                [section.items addObject:user];
                            }
                        }
                    }
                    
                    
                }                
            }else{  
                if (user.section == 0 ||user.section == 1 ) {
                    [contacts.items addObject:user];
                }else{
                    if (showOfflineUsers) {
                        if (groupOfflineUsers) {
                            [offline.items addObject:user];
                        }else{
                            [contacts.items addObject:user];
                        }
                    }
                }
                
            }
            
        }
        BOOL openFirst = NO;
        NSArray* sectionNames = [sectionDict.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];    
        for (NSString* sectionName in sectionNames) {
            SectionInfo* sectionInfo = [sectionDict objectForKey:sectionName];
            
            if(!openFirst){
                sectionInfo.open = YES;
                openFirst = YES;
            }
            
            NSNumber* state = [states objectForKey:sectionName]; 
            if (state){
                sectionInfo.open = state.boolValue;
            }
            
            
            if(sectionInfo.items.count>0 || showEmptyGroup){
                [self.sections addObject:sectionInfo];
                
            }
        }
        if(contacts.items.count>0){
            NSNumber* state = [states objectForKey:contacts.sectionName]; 
            if (state){
                contacts.open = state.boolValue;
            }
            [self.sections addObject:contacts];
            
        }
        
        if(offline.items.count>0){
            NSNumber* state = [states objectForKey:offline.sectionName]; 
            if (state){
                offline.open = state.boolValue;
            }
            [self.sections addObject:offline];
        }
    }
    @catch (NSException *exception) {
        DDLogError(@"Exception: %e", exception);
    }
    @finally {
        
    }    
}

- (void)reloadData {

    [self loadRosters];
    if (self.searchDisplay.active) {
        [self.searchDisplay.searchResultsTableView reloadData];
    }else{
        [self.tableView reloadData];
    }
    
}


#pragma mark - NSFetchedResultsControllerDelegate
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    if(self.active){
        [self reloadData];
        [self reloadAvatar];
    }

}


#pragma mark - UITableViewDataSource

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    
    /*
     Create the section header views lazily.
     */
	SectionInfo *sectionInfo = [self.sections objectAtIndex:section];
    if (!sectionInfo.headerView) {
        sectionInfo.headerView = [[[SectionHeaderView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.tableView.bounds.size.width, HEADER_HEIGHT) title:[NSString stringWithFormat:@"%@ (%i)",sectionInfo.sectionName,sectionInfo.items.count] section:section open: sectionInfo.open delegate:self] autorelease];
    }
    
    return sectionInfo.headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return DEFAULT_ROW_HEIGHT;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _sections ? _sections.count : 1;
}


- (NSString *)tableView:(UITableView *)sender titleForHeaderInSection:(NSInteger)sectionIndex
{
    SectionInfo* sectionInfo = [_sections objectAtIndex:sectionIndex];	
    return sectionInfo.sectionName;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
    SectionInfo* sectionInfo = [_sections objectAtIndex:sectionIndex];	
    return sectionInfo.open ? sectionInfo.items.count : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
	static NSString *CellIdentifier = @"RosterCell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil)
	{
		
        cell = [[[RosterCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:CellIdentifier] autorelease];
	}
	
    [self configureCell:cell forIndexPath:indexPath];
	
	return cell;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
        XMPPUserCoreDataStorageObject *user = [self userForRowAtIndexPath:indexPath];
    if (TTIsPad()) {
         [[NSNotificationCenter defaultCenter] postNotificationName:kChatSwitchNotification object:user];
    }else{
        NSString* url= [NSString stringWithFormat:@"gabber://chat/%@", user.jidStr];
        TTOpenURLFromView(url, tableView);
    }

}

- (void)tableView:(UITableView*)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath {
    XMPPUserCoreDataStorageObject *user = [self userForRowAtIndexPath:indexPath];
    NSString* url= [NSString stringWithFormat:@"gabber://vcard/%@", user.jidStr];
    TTOpenURLFromView(url, tableView);
//    TTOpenURL(url);
}


#pragma mark - Configuring table view cells
- (XMPPUserCoreDataStorageObject*) userForRowAtIndexPath:(NSIndexPath*)indexPath {
    if (_sections) {
        SectionInfo* sectionInfo = [_sections objectAtIndex:indexPath.section];
        return [sectionInfo.items objectAtIndex:indexPath.row];
        
    } else {
        return nil;
    }
}

- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath 
{
    if ([cell isKindOfClass:[RosterCell class]]){
        RosterCell* rosterCell =  (RosterCell*)cell;
        XMPPUserCoreDataStorageObject *user = [self userForRowAtIndexPath:indexPath];
        rosterCell.user = user;
        rosterCell.accessoryView = [self makeDetailDisclosureButton];
    }
}

#pragma mark - Cell accessoryView
- (UIButton *) makeDetailDisclosureButton 
{ 
    
    UIImage *image = [UIImage imageNamed:@"vcard"];
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [button setImage:image forState:UIControlStateNormal];
    CGRect frame = CGRectMake(0.0, 0.0, DEFAULT_ROW_HEIGHT, DEFAULT_ROW_HEIGHT);
    button.frame = frame;
    [button addTarget: self 
               action: @selector(accessoryButtonTapped:withEvent:) 
     forControlEvents: UIControlEventTouchUpInside]; 
    return ( button ); 
} 

- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event 
{ 
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]]; 
    if ( indexPath == nil ) 
        return; 
    if (TTIsPad()) {
        XMPPUserCoreDataStorageObject *user = [self userForRowAtIndexPath:indexPath];
        NSString* url= [NSString stringWithFormat:@"gabber://vcard/%@", user.jidStr];
        
        TTURLAction* action = [[[[TTURLAction actionWithURLPath:url] applySourceView:button] applySourceRect:CGRectMake(0, 0, button.width, button.height)]applyAnimated:YES];
        [[TTNavigator navigator] openURLAction:action];
    }else{
        [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath]; 
    }

} 

- (void) avatarTapped:(UITapGestureRecognizer *) recognizer;
{
    NSString* url= [NSString stringWithFormat:@"gabber://vcard/%@", [[[[XMPPClient sharedInstance] xmppStream] myJID] bare]];
    
    if (TTIsPad()) {
        
        TTURLAction* action = [[[[TTURLAction actionWithURLPath:url] applySourceView:self.rosterTitleView.avatarView] applySourceRect:CGRectMake(0, 0, self.rosterTitleView.avatarView.width, self.rosterTitleView.avatarView.height)]applyAnimated:YES];
        [[TTBaseNavigator navigatorForView:self.tableView] openURLAction:action];
    }else{
        TTOpenURLFromView(url, self.tableView);
    }
    
}


#pragma mark - SectionHeaderViewDelegate

-(void)sectionHeaderView:(SectionHeaderView*)sectionHeaderView sectionOpened:(NSInteger)sectionOpened {
	
	SectionInfo *sectionInfo = [self.sections objectAtIndex:sectionOpened];
	
	sectionInfo.open = YES;
    
    /*
     Create an array containing the index paths of the rows to insert: These correspond to the rows for each quotation in the current section.
     */
    NSInteger countOfRowsToInsert = [sectionInfo.items count];
    NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < countOfRowsToInsert; i++) {
        [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:sectionOpened]];
    }
    
    // Style the animation so that there's a smooth flow in either direction.
    UITableViewRowAnimation insertAnimation;
    
    insertAnimation = UITableViewRowAnimationTop;
    // Apply the updates.
    if (self.searchDisplay.active){
        [self.searchDisplay.searchResultsTableView beginUpdates];
        [self.searchDisplay.searchResultsTableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:insertAnimation];
        [self.searchDisplay.searchResultsTableView endUpdates];
    }else{
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:insertAnimation];
        [self.tableView endUpdates];
    }
    
    [indexPathsToInsert release];
}


-(void)sectionHeaderView:(SectionHeaderView*)sectionHeaderView sectionClosed:(NSInteger)sectionClosed {
    
    /*
     Create an array of the index paths of the rows in the section that was closed, then delete those rows from the table view.
     */
	SectionInfo *sectionInfo = [self.sections objectAtIndex:sectionClosed];
	
    sectionInfo.open = NO;
    NSInteger countOfRowsToDelete;
    if (self.searchDisplay.active){
        countOfRowsToDelete =  [self.searchDisplay.searchResultsTableView numberOfRowsInSection:sectionClosed];
    }else{
        countOfRowsToDelete  = [self.tableView numberOfRowsInSection:sectionClosed];
    }
    if (countOfRowsToDelete > 0) {
        NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
            
            [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:sectionClosed]];
        }
        if (self.searchDisplay.active){
            [self.searchDisplay.searchResultsTableView beginUpdates];
            [self.searchDisplay.searchResultsTableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
            [self.searchDisplay.searchResultsTableView endUpdates];
        }else{
            [self.tableView beginUpdates];
            [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
            [self.tableView endUpdates];

        }

        [indexPathsToDelete release];
    }
}


- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    searchBar.text = nil;
    [self fetchRosters];
    [self reloadData];
}

#pragma mark -  UISearchDisplayController Delegate Methods
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView{ 
    tableView.sectionHeaderHeight = HEADER_HEIGHT;

    

}




- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 
    [self fetchRosters];
    [self loadRosters];
    return YES;
}

-(void) handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer
{
    DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD ,recognizer); 
    if (UISwipeGestureRecognizerDirectionRight == recognizer.direction){
        [[XMPPClient sharedInstance] goAway];
        [self.rosterTitleView setStatus:@"离开"];
        [self.rosterTitleView setIntShow:2];
        
    }else if (UISwipeGestureRecognizerDirectionLeft == recognizer.direction){
        [[XMPPClient sharedInstance] goOnline];
        if(TTIsPad()){
            [self.rosterTitleView setStatus:@"iPad在线"]; 
            
        }else{
            [self.rosterTitleView setStatus:@"iPhone在线"]; 
            
        }
        [self.rosterTitleView setIntShow:3];
    }
    
    
    
}

- (void)handleSettingsChanged:(NSNotification *)notification
{
    [self reloadData];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [[XMPPClient sharedInstance] disconnect];
        TTOpenURL(@"gabber://login");
    }
}


@end
